#!/bin/bash

# update sources
echo "Updating Sources..."
cd "${WORKDIR}"
[ ! -d "${DEST}" ] && mkdir -p "${DEST}"

# parse deps
echo "  |- parse deps"
mvn dependency:list -Dsort=true                                         \
    | grep -E '^\[INFO\]\s*\S+:\S+:\S+:\S+:\S+\s*$'                     \
    | sed -r 's/^\[INFO\]\s*(\S+):(\S+):(\S+):(\S+):(\S+)\s*$/\2-\4/g'  \
    > "${DEST}/dep.list.new"

# copy deps
echo "  |- copy deps"
mvn dependency:copy-dependencies -Dclassifier=sources -DoutputDirectory="${DEST}/deps" &> /dev/null
if [ "$?" -ne 0 ]; then
    echo "  |- copy deps failed,exited"
    exit 1
fi

# comparison new and old deps
[ ! -d "${DEST}/sources" ] && mkdir "${DEST}/sources"
cd "${DEST}/sources"

begin_time=`date +%s`
while read line
do
    if [ -f "${DEST}/deps/${line}-sources.jar" -o -f "${DEST}/deps/${line}.jar" ]; then
        flag="1"
        if [ -f "${DEST}/dep.sources.list" ]; then
            for old_line in `cat "${DEST}/dep.sources.list"`
            do
                if [ x"${old_line}" = x"${line}" ]; then
                    flag="2"
                    break
                fi
            done
        fi
        if [ x1 = x"${flag}" ]; then
            if [ -f "${DEST}/deps/${line}-sources.jar" ]; then
                echo "  |- uncompress ${line}-sources.jar to ${DEST}/sources"
                jar -xf "${DEST}/deps/${line}-sources.jar"
            else
                echo "  |- decompile ${line}.jar"
                ${TOOLS}/decompiler/jd-cli "${DEST}/deps/${line}.jar" "${DEST}/sources" &> /dev/null
                [ "$?" -ne 0 ] && echo "  |- decompile ${line}.jar failed"
            fi
        fi
    else
        echo "  |- ${line}.jar not exists"
    fi
done < "${DEST}/dep.list.new"
end_time=`date +%s`

# process tags by langugage
cost_time=$((${end_time}-${begin_time}))
if [ $((${cost_time}%60)) -gt 0 ]; then
    cost_min=$((${cost_time}/60+1))
elif [ $((${cost_time}%60)) -eq 0 ]; then
    cost_min=$(((${cost_time})/60))
else
    cost_min=0
fi
[ "${cost_min}" -eq 0 ] && cost_min=1

cd "${DEST}"
if [ -f "${DEST}/tags" ]; then
    echo "  |- append to ${DEST}/tags"
    find "${DEST}/sources" -type f -name '*.java' -cmin -"${cost_min}"     \
        | ctags --fields=+iazSKlmn --extra=+qf -a "${DEST}/tags" -L -
else
    echo "  |- generate ${DEST}/tags"
    find "${DEST}/sources" -type f -name '*.java' -cmin -"${cost_min}"     \
        | ctags --fields=+iazSKlmn --extra=+qf -L -
fi

# replace old dep.sources.list
echo "  |- move ${DEST}/dep.list.new to ${DEST}/dep.sources.list"
mv -f "${DEST}/dep.list.new" "${DEST}/dep.sources.list"

# uncompress jar
echo "  |- done!"
